<?php

/**
 * EmsContent form.
 *
 * @package    ems1
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class EmsContentForm extends BaseEmsContentForm
{
    public function configure()
    {
        unset (
            $this['created_at'], $this['updated_at'], $this['type_id'],
            $this['is_enabled'], $this['published']
        );

        $this->widgetSchema['section_id'] = new sfWidgetFormInputHidden();

        $this->validatorSchema['title']->setMessage('required', 'Campo obligatorio. Debe indicar el titulo del contenido.');

        $this->setWidget('thumb_small', new sfWidgetFormInputHidden());

        $this->setValidator('thumb_small',new sfValidatorString(array('required' => false)));

        $this->setWidget('thumb_small_type', new sfWidgetFormInputHidden());

        $this->setValidator('thumb_small_type',new sfValidatorString(array('max_length' => 100, 'required' => false)));

        $this->setWidget('thumb_small_size', new sfWidgetFormInputHidden());

        $this->setValidator('thumb_small_size',new sfValidatorInteger(array('required' => false)));

        $this->setWidget('thumb_small_tmp', new sfWidgetFormInputFile());

        $this->widgetSchema->setHelp('thumb_small_tmp','Debe cargar un archivo de formato .jpg y de dimensiones 40x40 pixeles.');

        $this->setValidator('thumb_small_tmp',new sfValidatorString(array('required' => false)));

        $this->setWidget('thumb_big', new sfWidgetFormInputHidden());

        $this->setValidator('thumb_big',new sfValidatorString(array('required' => false)));

        $this->setWidget('thumb_big_type', new sfWidgetFormInputHidden());

        $this->setValidator('thumb_big_type',new sfValidatorString(array('max_length' => 100, 'required' => false)));

        $this->setWidget('thumb_big_size', new sfWidgetFormInputHidden());

        $this->setValidator('thumb_big_size',new sfValidatorInteger(array('required' => false)));

        $this->setWidget('thumb_big_tmp', new sfWidgetFormInputFile());

        $this->widgetSchema->setHelp('thumb_big_tmp','Debe cargar un archivo de formato .jpg y de dimensiones 100x100 pixeles.');

        $this->setValidator('thumb_big_tmp',new sfValidatorString(array('required' => false)));

        $this->setWidget('slug', new sfWidgetFormInputHidden());

        if ($this->object->exists())
        {
            $this->widgetSchema['published'] = new sfWidgetFormInputCheckbox(array('label' => 'Publicado'));
            $this->validatorSchema['published'] = new sfValidatorBoolean();
            $this->widgetSchema['is_enabled'] = new sfWidgetFormInputCheckbox(array('label' => 'Habilitado'));
            $this->validatorSchema['is_enabled'] = new sfValidatorBoolean();

            $defaults = array();
            
            if($this->getObject()->getThumbSmall()){
                $file = $this->getObject()->getThumbSmall();

                $folder = sfConfig::get('sf_upload_dir').'/portal_'.$this->getOption('portal_id').'/images/';

                $file_size = filesize($folder.$file);

                if(is_file($folder.$file)){
                    $file_size = filesize($folder.$file);

                    $defaults['thumb_small_size'] = $file_size;
                } else {
                    $defaults['thumb_small_size'] = 0;
                }
            }

            if($this->getObject()->getThumbBig()){
                $file = $this->getObject()->getThumbBig();

                $folder = sfConfig::get('sf_upload_dir').'/portal_'.$this->getOption('portal_id').'/images/';

                if(is_file($folder.$file)){
                    $file_size = filesize($folder.$file);

                    $defaults['thumb_big_size'] = $file_size;
                } else {
                    $defaults['thumb_big_size'] = 0;
                }
            }

            $this->setDefaults($defaults);
        }

        $this->widgetSchema->setLabels(
            array(
                'title'           => 'Titulo',
                'thumb_small_tmp' => 'Imagen pequeña',
                'thumb_big_tmp'   => 'Imagen grande',
                'author'          => 'Autor',
                'summary'         => 'Reseña',
                'can_comment'     => 'Con comentarios',
                'position'        => 'Posición'
            ));

        switch ($this->getObject()->getType()->getType()) {
            case 'Article':
                if(!$this->getObject()->getArticle()){
                    $article = new EmsArticle();
                    $this->getObject()->setArticle($article);
                }
                $form = new EmsArticleForm($this->getObject()->getArticle(), array('portal_id' => $this->getOption('portal_id')));
                $this->embedForm('Article', $form);
                break;
            case 'Video':
                if(!$this->getObject()->getVideo()){
                    $video = new EmsVideo();
                    $this->getObject()->setVideo($video);
                }
                $form = new EmsVideoForm($this->getObject()->getVideo(), array('portal_id' => $this->getOption('portal_id')));
                $this->embedForm('Video', $form);
                break;
            case 'Image':
                if(!$this->getObject()->getImage()){
                    $image = new EmsImage();
                    $this->getObject()->setImage($image);
                }
                $form = new EmsImageForm($this->getObject()->getImage(), array('portal_id' => $this->getOption('portal_id')));
                $this->embedForm('Image', $form);
                break;
            case 'Sound':
                if(!$this->getObject()->getSound()){
                    $sound = new EmsSound();
                    $this->getObject()->setSound($sound);
                }
                $form = new EmsSoundForm($this->getObject()->getSound(), array('portal_id' => $this->getOption('portal_id')));
                $this->embedForm('Sound', $form);
                break;
            default:
                break;
        }

        $this->validatorSchema->setPostValidator(
            new sfValidatorDoctrineUnique(
                    array('model' => 'EmsContent', 'column' => array('section_id','title')),
                    array('invalid' => 'Existe otro contenido en esta sección con el mismo Titulo.')
                )
            );
    }

    public function bind(array $taintedValues = null, array $taintedFiles = null)
    {
        $taintedValues['slug']= Slug::slugger($taintedValues['title']);

        parent::bind($taintedValues, $taintedFiles);
    }

    protected function doUpdateObject($values)
    {
        $thumb_types = array('small', 'big');
        foreach ($thumb_types as $key => $type) {
            if(strcasecmp($values['thumb_'.$type],'') != 0){
                $path_parts_file = pathinfo($values['thumb_'.$type]);

                $folder = sfConfig::get('sf_upload_dir').'/portal_'.$this->getOption('portal_id');

                $actual = ($type == 'small' ? $this->getObject()->getThumbSmall() : $this->getObject()->getThumbBig());

                if(!$this->getObject()->exists() || strcasecmp($path_parts_file['basename'], $actual) != 0){
                   $values['thumb_'.$type] = $this->saveUploadedFile(
                                    $path_parts_file['basename'],
                                    $values['thumb_'.$type.'_type'],
                                    $values['thumb_'.$type],
                                    $values['thumb_'.$type.'_size'],
                                    $folder.'/images/'
                                );
                }
            }
        }

        unset(
            $values['thumb_small_type'], $values['thumb_small_size'], $values['thumb_small_tmp'],
            $values['thumb_big_type'], $values['thumb_big_size'], $values['thumb_big_tmp']
        );

        parent::doUpdateObject($values);
    }

    protected function saveUploadedFile($originalName, $type, $tempName, $size, $path) {

        $validated_file = new sfValidatedFile($originalName, $type, $tempName, $size, $path);

        return $validated_file->save();
    }
}
